<template>
  <div>
    <div class="supplier" v-if="!supplierAddShow && !evaluateAddShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-hasPermi="['system:supplier:query']"
          class="btn search"
          @click="getSupplierList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          class="btn search"
          v-hasPermi="['system:supplier:add']"
          @click="
            supplierAddShow = true;
            pageType = 'add';
          "
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >新增</el-button
        >
        <el-button class="btn add" @click="handleRefresh"
          ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
          >重置</el-button
        >
        <el-popover :width="170" trigger="click" placement="bottom">
          <template #reference>
            <el-button class="btn search" style="width: 100px"
              ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
              >显示列</el-button
            >
          </template>
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div>
              <el-checkbox label="supplierCode">供应商编号</el-checkbox>
            </div>
            <div>
              <el-checkbox label="supplierAbbreviation">供应商缩写</el-checkbox>
            </div>
            <div>
              <el-checkbox label="supplierName">供应商全称</el-checkbox>
            </div>
            <div>
              <el-checkbox label="provinceName">供应商地址</el-checkbox>
            </div>
            <div>
              <el-checkbox label="supplierAddress">供应商详细地址</el-checkbox>
            </div>
            <div>
              <el-checkbox label="purchaseNumber">已购产品数量</el-checkbox>
            </div>
            <div>
              <el-checkbox label="totalQuantity">已购买次数</el-checkbox>
            </div>
            <div>
              <el-checkbox label="contractAmount">已购买金额(元)</el-checkbox>
            </div>
            <div>
              <el-checkbox label="evaluationGradeName">评价等级</el-checkbox>
            </div>
            <div>
              <el-checkbox label="supplierSourceName">来源</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-popover>
      </div>
      <!-- 筛选条件 -->
      <div class="search">
        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.supplierCode"
            class="search-input"
            maxlength="30"
            placeholder="请输入供应商编号"
          ></el-input>
        </div>
        <!-- <div class="search-item">
          <el-input
            clearable
            v-model="params.productName"
            class="search-input"
            maxlength="30"
            placeholder="请输入主供应产品"
          ></el-input>
        </div> -->
        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.supplierName"
            class="search-input"
            maxlength="30"
            placeholder="请输入供应商全称"
          ></el-input>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.evaluationGrade"
            placeholder="请选择评价等级"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in gradeList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.supplierSource"
            placeholder="请选择来源"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in sourceList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
      </div>

      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="supplierList"
        border
        height="64vh"
        :header-cell-style="{ 'text-align': 'center', background: 'red' }"
        @sort-change="sortChange"
      >
        <!-- 操作模式 -->
        <el-table-column
          label="操作"
          :show-overflow-tooltip="true"
          width="180px"
        >
          <template #default="{ row }">
            <div class="table-operate">
              <el-icon
                v-hasPermi="['system:supplier:edit']"
                title="编辑"
                color="#FFB700"
                class="table-icon"
                :size="20"
                @click="handleOperate('edit', row)"
              >
                <Edit />
              </el-icon>
              <el-icon
                v-hasPermi="['system:supplier:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <el-icon
                v-hasPermi="['system:supplier:evaluate']"
                title="评价"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('evaluate', row)"
              >
                <Star />
              </el-icon>
              <el-icon
                v-hasPermi="['system:supplier:remove']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
            </div> </template
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="70"
          align="center"
        />
        <el-table-column
          label="供应商编号 "
          prop="supplierCode"
          :show-overflow-tooltip="true"
          min-width="90"
          v-if="checkList.includes('supplierCode')"
          sortable="custom"
        />
        <el-table-column
          label="供应商缩写"
          prop="supplierAbbreviation"
          :show-overflow-tooltip="true"
          min-width="90"
          v-if="checkList.includes('supplierAbbreviation')"
          sortable="custom"
        />
        <el-table-column
          label="供应商全称"
          prop="supplierName"
          :show-overflow-tooltip="true"
          min-width="100"
          v-if="checkList.includes('supplierName')"
          sortable="custom"
        />
        <el-table-column
          label="供应商地址"
          prop="provinceName"
          :show-overflow-tooltip="true"
          min-width="140"
          v-if="checkList.includes('provinceName')"
          sortable="custom"
        >
          <template #default="{ row }">
            {{ row.location }}
          </template>
        </el-table-column>
        <el-table-column
          label="供应商详细地址"
          prop="supplierAddress"
          :show-overflow-tooltip="true"
          min-width="140"
          v-if="checkList.includes('supplierAddress')"
          sortable="custom"
        />
        <el-table-column
          label="已购产品数量"
          prop="purchaseNumber"
          :show-overflow-tooltip="true"
          min-width="80"
          v-if="checkList.includes('purchaseNumber')"
        />
        <el-table-column
          label="已购买次数"
          prop="totalQuantity"
          :show-overflow-tooltip="true"
          min-width="80"
          v-if="checkList.includes('totalQuantity')"
        />
        <el-table-column
          label="已购买金额(元)"
          prop="contractAmount"
          :show-overflow-tooltip="true"
          min-width="100"
          v-if="checkList.includes('contractAmount')"
        />
        <el-table-column
          label="评价等级"
          prop="evaluationGradeName"
          :show-overflow-tooltip="true"
          min-width="80"
          v-if="checkList.includes('evaluationGradeName')"
          sortable="custom"
        />
        <el-table-column
          label="来源"
          prop="supplierSourceName"
          :show-overflow-tooltip="true"
          min-width="80"
          v-if="checkList.includes('supplierSourceName')"
          sortable="custom"
        />
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getSupplierList"
      />
    </div>
    <providerAdd
      v-if="supplierAddShow"
      ref="supplierAddRef"
      v-model:supplierAddShow="supplierAddShow"
      @updateEvaluateAddShow="evaluateAddShow = false"
      @refreshList="getSupplierList"
      :pageType="pageType"
    />
    <evaluateAdd
      ref="evaluateAddRef"
      v-model:evaluateAddShow="evaluateAddShow"
      @refreshList="getSupplierList"
      :pageType="pageType"
      v-if="evaluateAddShow"
    />
  </div>
</template>

<script setup>
import evaluateAdd from "./evaluateAdd.vue";
import providerAdd from "./providerAdd.vue";
import { getDictsApi } from "@/api/dict";
import {
  getSupplierListApi,
  deleteSupplierApi,
} from "@/api/information/supplier";
import { addTableHeaderApi, getTableHeaderApi } from "@/api/pub";
import { ElMessage, ElMessageBox } from "element-plus";
// 搜索参数
const params = reactive({
  supplierCode: "",
  productName: "",
  supplierName: "",
  evaluationGrade: null,
  supplierSource: null,
  pageNum: 1,
  pageSize: 50,
  sortField: "",
  sortOrder: "",
});
const checkList = ref([
  "supplierCode",
  "supplierAbbreviation",
  "supplierName",
  "provinceName",
  "supplierAddress",
  "purchaseNumber",
  "totalQuantity",
  "contractAmount",
  "evaluationGradeName",
  "supplierSourceName",
]);
// 表格加载效果
const loading = ref(false);
// 供应商新增组件显隐
const supplierAddShow = ref(false);
// 评价组件显隐
const evaluateAddShow = ref(false);
// 供应商列表
const supplierList = ref([]);
// 总数
const total = ref(0);
// 供应商新增组件引用
const supplierAddRef = ref(null);
// 评价组件引用
const evaluateAddRef = ref(null);
// 操作类型
const pageType = ref("");
// 等级列表
const gradeList = ref([]);
// 来源列表
const sourceList = ref([]);

/**
 * @description: 复选框选中
 */
const handleCheckChange = async (val) => {
  var str = val.join(",");
  const result = await addTableHeaderApi({
    moduleType: 1,
    titleField: str,
  });
  // getTableHeader();
};

/**
 * @description: 获取表头
 */
const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: 1,
  });
  if (result.code == 200) {
    var arr = result.data.titleField.split(",");
    checkList.value = arr;
  }
};

/**
 * @description: 获取供应商列表
 */
const getSupplierList = async () => {
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;
    const res = await getSupplierListApi({ pageNum, pageSize }, params);
    supplierList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

/**
 * @description: 重置
 */
const handleRefresh = () => {
  Object.assign(params, {
    supplierCode: "",
    productName: "",
    supplierName: "",
    evaluationGrade: null,
    supplierSource: null,
    pageNum: 1,
    pageSize: 50,
    sortField: "",
    sortOrder: "",
  });
  getSupplierList();
};
/**
 * @description: 列表排序
 * @param {*} column.prop //当前排序取的字段
 * @param {*} column.order // "desc" "asc" 正序或倒序
 */
const sortChange = (column) => {
  params.sortField = column.prop;
  if (column.order === "descending") {
    params.sortOrder = "DESC"; // 排序或倒序
  } else {
    params.sortOrder = "ASC"; // 排序或倒序
  }
  getSupplierList();
};
/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleOperate = async (type, row) => {
  switch (type) {
    case "edit":
      pageType.value = type;
      supplierAddShow.value = true;
      nextTick(() => {
        supplierAddRef.value.handleDetailInfo(row.supplierId);
      });
      break;
    case "detail":
      pageType.value = type;
      supplierAddShow.value = true;
      evaluateAddShow.value = true;
      nextTick(() => {
        supplierAddRef.value.handleDetailInfo(row.supplierId);
        evaluateAddRef.value.handleDetailInfo(row.supplierId);
      });
      break;
    case "evaluate":
      pageType.value = type;
      evaluateAddShow.value = true;
      nextTick(() => {
        evaluateAddRef.value.handleDetailInfo(row.supplierId);
      });
      break;
    case "delete":
      ElMessageBox.confirm("此操作将删除该供应商，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteSupplierApi(row.supplierId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getSupplierList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;

    default:
      break;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  await getDictsApi("evaluation_grade_type").then((res) => {
    // 等级
    if (res.code === 200) {
      gradeList.value = res.data;
    }
  });

  await getDictsApi("erp_supplier_source").then((res) => {
    // 来源
    if (res.code === 200) {
      sourceList.value = res.data;
    }
  });
}

/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  // 当前页码
  const currentPage = params.pageNum;
  // 每页显示的数据条数
  const pageSize = params.pageSize;
  // 当前行的实际索引
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  // 如果当前行的索引大于等于当前页的最大索引，
  // 则使用当前行的实际索引，否则使用当前行的原始索引
  return truelndex;
}

onMounted(() => {
  getTableHeader();
  getSupplierList();
  getDicts();
});
</script>
<style>
@import "@/assets/styles/confirmBtn.css";
</style>
<style lang="scss" scoped>
.supplier {
  padding: 20px;
  width: 100%;
  height: 100%;
  .pagination {
    margin-top: 20px;
  }
}
</style>
